<template>
  <div>
    <t-card class="list-card-container">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="refresh" theme="default" variant="outline"><template #icon><RefreshIcon/></template>  刷新</t-button>
          
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </div>
        <div class="search-input">
          <t-space>
            <t-date-range-picker allow-input clearable @pick="onPick" @change="onPickChange" />
			<t-dropdown :options="searchItem" trigger="click" @click="clickHandler">
			      <t-space>
			        <t-button variant="text">
			          {{searchText}}
			          <template #suffix> <t-icon name="chevron-down" size="16" /></template>
			        </t-button>
			      </t-space>
			</t-dropdown>
			<t-space size="0px">
				<t-input v-model="searchKey" placeholder="请输入搜索内容" clearable>
				</t-input> 
				<t-button @click="search"><search-icon size="20px"/> 搜索</t-button>
			</t-space>
            
          </t-space>
        </div>
      </t-row>

      <t-table :data="data" :columns="BM_COLUMNS" row-key="id" vertical-align="top" :hover="true"
        :pagination="pagination" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange" @select-change="rehandleSelectChange">
        <template #interestData="{ row }" > 
			<t-space size="small">   
				<template v-for="item in row.interestData">
					 <t-tag v-if="getLabel(item)!=''" theme="primary" variant="outline"> {{getLabel(item)}} </t-tag>
				</template>
			</t-space>
        </template>
		<template #jun="{row}">
			<t-tag v-if="row.jun==='是'" theme="success">是</t-tag>
			<t-tag v-else>否</t-tag>
		</template>
        <template #interest="{row}"> 
		  <t-tag  theme="default" variant="light"> {{row.interest}} </t-tag>
        </template>
        <template #op="slotProps">
			<t-space>
				<a class="t-button-link" @click="openEdit(slotProps.row.id)">编辑</a>
				<t-popconfirm content="确认删除吗" @confirm="del(slotProps)">
				<a class="t-button-link">删除</a>
				</t-popconfirm>
			</t-space>
          
        </template>
      </t-table>
    </t-card>
  </div>
</template>

<script type="ts">
export default {
  name: 'BaomingList',
};
</script>
<script setup type="ts">
import { ref,reactive,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { SearchIcon,RefreshIcon,AddIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';

import { BM_COLUMNS,Interest_Data } from './constants';

import { useLocale } from '@/locales/useLocale';
import dayjs from 'dayjs'
import { getAllBm, saveBm ,deleteBm,searchBm} from '@/api/archives';
import {getSettingsList} from '@/api/settings'


const { locale } = useLocale();
const searchKey = ref('');
const searchWhere=ref('phone')
const router=useRouter();
const data = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});
const dataLoading = ref(false);
const selectedRowKeys = ref([]);
const searchItem=[
	{
		content:'手机号',
		value:"phone"
	},
	{
		content:'小区名',
		value:"area"
	},
	{
		content:'兴趣专长',
		value:"interest"
	}
]
const searchText=ref('手机号')
const clickHandler= (data) => { 
	//console.log(data)
  searchWhere.value=data.value
  searchText.value=data.content;
}
const search=()=>{
	//手机号 专长 小区名 日期
	var d={
		where:searchWhere.value,
		key:searchKey.value,
		page:1,
		pageSize:30
	}
	searchBm(d)
	.then(ret=>{
		data.value = ret.items;
		pagination.total = ret.totalItems;
		pagination.current = ret.currentPage;
	}) 
}
const del=(obj)=>{
	var id=obj.row.id
	deleteBm(id)
	.then(ret=>{
		refresh()
	})
}
const fetchData = async (d) => {
  dataLoading.value = true;
  try {
    const {items,totalItems,currentPage}=await getAllBm(d);
    data.value = items;
    pagination.total = totalItems;
    pagination.current = currentPage;
  } catch (e) {
    if (e.message) {
      MessagePlugin.error(e.message);
    } else {
      MessagePlugin.error(e.msg);
    }
  } finally {
    dataLoading.value = false;
  }
};
// 刷新数据
const refresh = async () => {
  pagination.current = 1;
  await fetchData(pagination);
};
const getLabel=(data)=>{
	let label=''
	for(let i=0;i<intersertData.value.length;i++)
	{
		let item=intersertData.value[i]
		if(item.value==data)
		{
			label=item.label
			break; 
		}
	}
	return label;
}
const rehandlePageChange = (pageInfo) => {
  console.log(`rehandlePageChange${JSON.stringify(pageInfo)}`);
  pagination.current = pageInfo.current;
  pagination.pageSize = pageInfo.pageSize;
  fetchData(pageInfo);
};

const rehandleSelectChange = (val) => {
  selectedRowKeys.value = val;
};

const openEdit=(id)=>{
  const params={id:id}
  router.push({
    name:'postsEdit',
    params:{id:id}
  })
}

const intersertData=ref([])
const fetchIntersertData=()=>{
	getSettingsList('bm-interest')
	.then(ret=>{
		if(ret&&ret[0])
		{
			var json=ret[0].value.replaceAll("\\n","").replaceAll("\\","").replaceAll(" ","");
			 if (json.startsWith('"')) {
			        // 使用 slice 方法去掉首尾引号
			        json= json.slice(1, -1);
			}
			if (json.endsWith('"')) {
				       // 使用 slice 方法去掉首尾引号
				       json= json.slice(1, -1);
				   }
			 
			intersertData.value=JSON.parse(json)   
		}
	})
}

onMounted(async () => {
	fetchIntersertData()
  await fetchData({
    current: pagination.current,
    pageSize: pagination.pageSize,
  });

});


// 日期选择
const onPick = (value, context) => console.log('onPick:', value, context);
const onPickChange = (value, context) => {
  console.log('onPickChange:', value, context);
  console.log(
    'timestamp:',
    context.dayjsValue.map((d) => d.valueOf()),
  );
  console.log(
    'YYYYMMDD:',
    context.dayjsValue.map((d) => d.format('YYYYMMDD'))
  );

   fetchData({
    current: pagination.current,
    pageSize: pagination.pageSize,
    date:`${value[0],value[1]}`
  });
};

</script>

<style lang="less" scoped>

</style>
